package com.smart.campus.security;

import com.smart.campus.dto.SysMenu;
import com.smart.campus.dto.SysUser;
import com.smart.campus.service.SysMenuServiceFeign;
import com.smart.campus.service.SysUserServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserServiceFeign sysUserServiceFiegn;

    @Autowired
    private SysMenuServiceFeign sysMenuServiceFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.通过当前登录人获得当前用户信息
        SysUser sysUser = sysUserServiceFiegn.findSysUserByUserName(username);
        if (Objects.isNull(sysUser)) {
            throw new RuntimeException("用户名或密码错误");
        }
//
        List<String> permissions = null;
        //如果当前登录人是admin，我们给当前登录人赋所有权限
        if (sysUser.getUserName().equals("admin")) {
            List<SysMenu> sysMenus = sysMenuServiceFeign.findSysMenuList(new SysMenu());
            permissions = sysMenus.stream()
                        .map(item -> item.getPerms())
                        .distinct()
                        .filter(s -> s != "")
                        .collect(Collectors.toList());
            // TODO 查询为空
        } else {
            permissions  = sysMenuServiceFeign.selectPermsByUserId(sysUser.getUserId());
        }
        return new LoginUser(sysUser, permissions);
    }
}
